package functions.mams_rest;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.LoggerFactory;
import com.beans.ORGBean;
import coms.AutoException;
import coms.Constants;
import coms.process.LoginTest;
import frame.FrameWork;
import frame.HttpHelper;

/**
 * 
 * @author CHENHAILIAN6
 *
 */
public class Org {
  private org.slf4j.Logger logger = LoggerFactory.getLogger(Org.class);
  ORGBean selectOrg;
  boolean isPassed = false;

  ArrayList<ORGBean> companyOrgs;

  public ORGBean getSelectOrg() {
    return selectOrg;
  }

  public void setSelectOrg(ORGBean selectOrg) {
    this.selectOrg = selectOrg;
  }

  public String getResult() {
    return result;
  }

  public void setResult(String result) {
    this.result = result;
  }

  String result;

 

  public ORGBean getOrgByName(ArrayList<ORGBean> orgs, String name) {

    ORGBean bean = null;
    if (orgs != null && orgs.size() > 0) {
      for (int i = 0; i < orgs.size(); i++) {
        ORGBean org = orgs.get(i);
        if (org.getTitle().equals(name)) {
          bean = org;
          break;
        }
      }
    }
    return bean;

  }


  /**
   * 华润重庆医药有限公司
   * 
   * @param path
   * @return
   */
  public ORGBean getOrgByCompanyName(String companyName) {
    logger.info("通过公司名查询组织 ----------------- start ------------");
    ORGBean bean = null;
    String urlCompanyName = "";
    try {
      urlCompanyName = java.net.URLEncoder.encode(companyName, "utf-8");
    } catch (UnsupportedEncodingException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    String url = Constants.FIND_ORG_URL + "/" + urlCompanyName;
    try {
      result = HttpHelper.post("", url);
      logger.info("getOrgByCompanyName --- " + result);
      isPassed = HttpHelper.isOk;
      logger.info("getOrgByCompanyName : " + String.valueOf(isPassed));
      if (isPassed) {
        JSONArray array = new JSONArray(result);
        if (array.length() == 0) {
          logger.error("通过公司名称" + companyName + "查询公司： 无数据");
          isPassed = false;
        } else {
          // ArrayList<OrgBean> orgs = new ArrayList<OrgBean>();
          boolean hasChildren = true;
          while (hasChildren) {
            JSONObject object = array.getJSONObject(0);
            array = object.getJSONArray("children");
            String code = object.getString("code");
            String expand = String.valueOf(object.getBoolean("expand"));
            String id = object.getString("id");
            String employee = String.valueOf(object.getBoolean("employee"));
            String orgPath = object.getString("orgPath");
            String title = object.getString("title");
            ORGBean temp = new ORGBean(expand, code, orgPath, array, id, employee, title);
            logger.info("得到 -- " + temp.toString());
            logger.info(
                title + "--" + companyName + "--" + String.valueOf(title.equals(companyName)));
            if (title.equals(companyName)) {
              hasChildren = false;
              bean = temp;
              logger.info(" company : " + bean.toString());
              break;
            }
            if (array.length() == 0) {
              hasChildren = false;
              // logger.error("通过公司名称"+ companyName+ "查询公司： 无数据" );
            }

          }
        }
      } else {
        logger.info("getOrgByCompanyName : " + String.valueOf(isPassed));
      }
    } catch (Exception e) {

    }


    return bean;
  }

  /**
   * 返回公司的某个部门 华润重庆医药有限公司
   * 
   * @param companyName
   */
  public void getOrg(String companyName) {

    ORGBean companyBean = getOrgByCompanyName(companyName);
    if (isPassed) {
      String companyOrgId = companyBean.getId();
      String url = Constants.FIND_SUB_ORG_URL + "/" + companyOrgId;

      try {
        result = HttpHelper.post("", url);
        logger.info("getOrg --- " + result);
        isPassed = HttpHelper.isOk;
        if (isPassed) {
          JSONArray array = new JSONArray(result);
          if (array.length() == 0) {
            logger.error("通过公司名称" + companyName + "查询组织机构： 无数据");
            isPassed = false;
          } else {
            companyOrgs = new ArrayList<ORGBean>();

            for (int i = 0; i < array.length(); i++) {
              JSONObject object = array.getJSONObject(i);
              // array = object.getJSONArray("children");
              String code = object.getString("code");
              String expand = String.valueOf(object.getBoolean("expand"));
              String id = object.getString("id");
              String employee = String.valueOf(object.getBoolean("employee"));
              String orgPath = object.getString("orgPath");
              String title = object.getString("title");
              ORGBean bean1 = new ORGBean(expand, code, orgPath, null, id, employee, title);
              companyOrgs.add(bean1);

            }

          }
        }
      } catch (Exception e) {

        // e.printStackTrace();

      }
    } else {
      logger.error("通过公司查询不到数据");
    }

  }

  /**
   * 返回公司的某个部门 华润重庆医药有限公司->重庆医药-质管部
   * 
   * @param companyName
   * @param deptName
   * @return
   */
  public ORGBean getRandomOrg(String companyName, String deptName) {
    logger.info("getRandomOrg params : companyName="+companyName +", deptName="+deptName);
    if (companyOrgs == null) {
      getOrg(companyName);
    }
    if (companyOrgs.size() < 1) {
      isPassed = false;
    } else {
      for (int i = 0; i < companyOrgs.size(); i++) {
        ORGBean dept = companyOrgs.get(i);
        String title = dept.getTitle();
        logger.info("company has：dept " + title);
        if (title.trim().equals(deptName.trim())) {
          
          selectOrg = dept;
          logger.info("selectOrg : " + selectOrg.toString());
          break;
        }
      }
   
      int size = companyOrgs.size();
      if (selectOrg == null) {
        logger.info("找不到该部门，将随机选取一个部门");
        if (size == 1) {
          selectOrg = companyOrgs.get(0);
        }else {
        Random dom = new Random(size);
        int next = dom.nextInt(size - 1);
        selectOrg = companyOrgs.get(next);
        logger.info("select org : "  + selectOrg.toString());
        }
      }
    }

    return selectOrg;

  }

  /**
   * 返回公司的某个部门 华润重庆医药有限公司->重庆医药-质管部
   * 
   * @param companyName
   * @param deptName
   * @return 有人的机构（此处为选择组员，选择人）
   */
  public ORGBean getHasEmployeesOrg(String companyName, String deptName) {
    selectOrg = null;
    if (companyOrgs == null) {
      getOrg(companyName);
    }
    if (companyOrgs.size() < 1) {
      isPassed = false;
    } else {
      for (int i = 0; i < companyOrgs.size(); i++) {
        ORGBean dept = companyOrgs.get(i);
        String title = dept.getTitle();
        if (title.equals(deptName)) {
          String id = dept.getId();
          ArrayList<ORGBean> subOrgBeans = findSubEmployeesByOrgId(id);
          if (subOrgBeans != null) {
            selectOrg = dept;
            break;
          } else {
            logger.info(deptName + " --- not employee ");
          }
        }
      }
      if (selectOrg == null) {
        logger.info("选择第一个有人员的部门");
        for (int i = 0; i < companyOrgs.size(); i++) {
          ORGBean dept = companyOrgs.get(i);
          String id = dept.getId();
          ArrayList<ORGBean> subOrgBeans = findSubEmployeesByOrgId(id);
          if (subOrgBeans != null) {
            selectOrg = dept;
            break;
          }
        }
        if (selectOrg == null) {
          isPassed = false;
          logger.error(companyName + " 没人 可选");
        }
      }
    }

    return selectOrg;
  }

  public ArrayList<ORGBean> findSubEmployeesByOrgId(String orgId) {
    ArrayList<ORGBean> subOrgBeans = null;
    String url = Constants.FIND_SUB_EMPLOYEES_URL + orgId;
    try {
      result = HttpHelper.post("", url);
      logger.info("findSubEmployeesByOrgId --- " + result);
      isPassed = HttpHelper.isOk;
      if (isPassed) {
        try {
          JSONArray array = new JSONArray(result);
          if (array.length() == 0) {
            logger.error("通过组织ID" + orgId + "查询组织组织无员工");
            isPassed = false;
          } else {
            subOrgBeans = new ArrayList<ORGBean>();
            for (int i = 0; i < array.length(); i++) {
              JSONObject object = array.getJSONObject(i);
              // array = object.getJSONArray("children");
              String code = object.getString("code");
              String expand = String.valueOf(object.getBoolean("expand"));
              String id = object.getString("id");
              String employee = String.valueOf(object.getBoolean("employee"));
              String orgPath = "";
              /**
               * orgPath 在查询出来是人的时候就不存在，所以需要加个异常处理
               */
              try {
                orgPath = object.getString("orgPath");
              } catch (Exception e) {

              }

              String title = object.getString("title");
              ORGBean bean1 = new ORGBean(expand, code, orgPath, null, id, employee, title);
              subOrgBeans.add(bean1);

            }
          }
        }catch(JSONException e) {
          logger.info("JSON解析错误");
        }
      }
    }catch(Exception e) {
      throw new AutoException("服务器异常");
    }
    return subOrgBeans;
  }
  
  /**
   * 通过id查找组织机构或者组织部门或者部门下的人员
   * 
   * @param id
   * @return
   */
  public ArrayList<ORGBean> findSubOrgsById(String orgId) {
    ArrayList<ORGBean> subOrgBeans = null;
    String url = Constants.FIND_SUB_ORG_URL + "/" + orgId;
    try {
      result = HttpHelper.post("", url);
      logger.info("findSubOrgsById --- " + result);
      isPassed = HttpHelper.isOk;
      if (isPassed) {
        try {
        JSONArray array = new JSONArray(result);
        if (array.length() == 0) {
          logger.error("通过公司名称" + orgId + "查询组织机构： 无数据");
          isPassed = false;
        } else {
          subOrgBeans = new ArrayList<ORGBean>();
          for (int i = 0; i < array.length(); i++) {
            JSONObject object = array.getJSONObject(i);
            // array = object.getJSONArray("children");
            String code = object.getString("code");
            String expand = String.valueOf(object.getBoolean("expand"));
            String id = object.getString("id");
            String employee = String.valueOf(object.getBoolean("employee"));
            String orgPath = "";
            /**
             * orgPath 在查询出来是人的时候就不存在，所以需要加个异常处理
             */
            try {
              orgPath = object.getString("orgPath");
            } catch (Exception e) {

            }

            String title = object.getString("title");
            ORGBean bean1 = new ORGBean(expand, code, orgPath, null, id, employee, title);
            subOrgBeans.add(bean1);

          }

        }
        }catch(JSONException e) {
          logger.error("JSON 解析错误");
        }
      }
    } catch (Exception e) {
      throw new AutoException("服务器异常");
      // e.printStackTrace();

    }



    return subOrgBeans;

  }
  
  /**
   * 返回公司的某个部门 华润重庆医药有限公司->重庆医药-质管部  -- 的员工
   * @param companyName
   * @param deptName
   * @return
   */
  public ArrayList<ORGBean> getUsers(String companyName, String deptName){
    ArrayList<ORGBean> empleeyBeans = null;
    ORGBean bean =  getHasEmployeesOrg(companyName, deptName);
    if(bean == null) {
      isPassed = false;
      logger.error("该公司下无员工");
    }else {
      empleeyBeans = findSubEmployeesByOrgId(bean.getId());
    }    
    return empleeyBeans;
  }
  
  /**
   * 部门里面的员工
   * @param deptBean
   * @return
   */
  public ArrayList<ORGBean> getDeptUsers(ORGBean deptBean){
    ArrayList<ORGBean> empleeyBeans = null;
    if(deptBean == null) {
      isPassed = false;
      logger.error("该公司下无员工");
    }else {
      empleeyBeans = findSubEmployeesByOrgId(deptBean.getId());
    }    
    return empleeyBeans;
  }
}
